<template>
    <el-dialog
        v-model="showflag"
        :title="title"
        width="50vw"
        align-center
        :close-on-click-modal="false"
        @close="resetdata">
        <div style="padding: 0 40px">
            <el-form
                ref="ruleFormRef"
                style="width: 100%"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
                class="demo-ruleForm"
                :size="formSize"
                status-icon>
                <div class="linebox">
                    <el-form-item label="公司名称" prop="name">
                        <el-input
                            v-model="ruleForm.name"
                            :disabled="!isedit"
                            placeholder="请输入公司名称" />
                    </el-form-item>
                    <el-form-item label="公司类型" prop="gslx">
                        <el-input
                            v-model="ruleForm.gslx"
                            :disabled="!isedit"
                            placeholder="请输入公司类型" />
                        <!-- <el-select
                            v-model="ruleForm.device_name"
                            placeholder="请选择"
                            :disabled="!isedit">
                            <el-option label="类型1" :value="1" />
                            <el-option label="类型2" :value="2" />
                        </el-select> -->
                    </el-form-item>
                </div>
                <div class="linebox">
                    <el-form-item label="公司状态" prop="isdel">
                        <el-radio-group v-model="ruleForm.isdel" :disabled="!isedit">
                            <el-radio :value="1">正常</el-radio>
                            <el-radio :value="2">注销</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="法人" prop="uname">
                        <el-input
                            v-model="ruleForm.uname"
                            :disabled="!isedit"
                            placeholder="请输入法人" />
                    </el-form-item>
                </div>
                <div class="linebox">
                    <el-form-item label="所属市" prop="city">
                        <el-select
                            @change="changcity"
                            v-model="ruleForm.city"
                            placeholder="请选择"
                            :disabled="!isedit">
                            <el-option
                                v-for="(item, index) in citylist"
                                :key="index"
                                :label="item.name"
                                :value="item.name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属区县" prop="area">
                        <el-select
                            v-model="ruleForm.area"
                            placeholder="请选择"
                            :disabled="!isedit">
                            <el-option
                                v-for="(item, index) in arealist"
                                :key="index"
                                :label="item.name"
                                :value="item.name" />
                        </el-select>
                    </el-form-item>
                </div>
                <div class="linebox">
                    <el-form-item label="成立日期" prop="cltime">
                        <el-date-picker
                            v-model="ruleForm.cltime"
                            :disabled="!isedit"
                            type="date"
                            placeholder="请选择"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="联系电话" prop="telphone">
                        <el-input
                            v-model="ruleForm.telphone"
                            :disabled="!isedit"
                            placeholder="请输入联系电话" />
                    </el-form-item>
                </div>
                <div class="linebox">
                    <el-form-item label="社会统一信用代码" prop="code">
                        <el-input
                            v-model="ruleForm.code"
                            :disabled="!isedit"
                            placeholder="请输入社会统一信用代码" />
                    </el-form-item>
                    <el-form-item label="注册地址" prop="address">
                        <el-input
                            v-model="ruleForm.address"
                            :disabled="!isedit"
                            placeholder="请输入注册地址" />
                    </el-form-item>
                </div>
                <div class="linebox">                    
                    <el-form-item label="经营范围" prop="jyfw" style="width: 100%;">
                        <el-input
                            v-model="ruleForm.jyfw"
                            :disabled="!isedit"
                            type="textarea"
                            :rows="4"
                            placeholder="请输入经营范围" />
                    </el-form-item>
                </div>
                <div class="linebox">
                    <el-form-item label="营业执照" prop="yyzz">
                        <el-upload
                            key="yyzz"
                            ref="yyzzupload"
                            class="avatar-uploader"
                            :action="baseURL + '/api/common/upload'"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                            name="file">
                            <img
                                v-if="ruleForm.yyzz"
                                :src="ruleForm.yyzz"
                                class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="经营许可证" prop="jyxkz">
                        <el-upload
                            key="jyxkz"
                            ref="jyxkzupload"
                            class="avatar-uploader"
                            :action="baseURL + '/api/common/upload'"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess2"
                            :before-upload="beforeAvatarUpload"
                            name="file">
                            <img
                                v-if="ruleForm.jyxkz"
                                :src="ruleForm.jyxkz"
                                class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </div>
                <div class="linebox">
                    <el-form-item label="登录账号" prop="username">
                        <el-input
                            v-model="ruleForm.username"
                            :disabled="!isedit"
                            placeholder="请输入登录账号" />
                    </el-form-item>
                    <el-form-item label="账号密码" prop="password">
                        <el-input
                            v-model="ruleForm.password"
                            :disabled="!isedit"
                            placeholder="默认密码：123456" />
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showflag = false">取消</el-button>
                <el-button
                    v-if="isedit"
                    type="primary"
                    @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, provide, reactive, toRaw, inject } from "vue";
import { ElMessage } from "element-plus";
import { post, baseURL } from "../../../api/request";
import type { FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { ElUpload } from "element-plus";

let showflag = ref(false);
let title = ref("新增公司");
let isedit = ref(true);
let device_id = ref("");
let token = ref("");
const getdata = inject<() => void>("getdata")!; //父组件的方法
const yyzzupload = ref<InstanceType<typeof ElUpload>>();
const jyxkzupload = ref<InstanceType<typeof ElUpload>>();
let citylist = ref([]);
let arealist = ref([]);

onMounted(() => {
    token.value = localStorage.getItem("token") || "";

    post({
        url: "/api/area/index",
        data: {
            parent_id: 3021,
        },
    }).then((res: any) => {
        citylist.value = res.data.list;
    });
});

const changcity = (e: any) => {
    let id = citylist.value.find((item: any) => item.name == e)?.id;
    post({
        url: "/api/area/index",
        data: {
            parent_id: id,
        },
    }).then((res: any) => {
        arealist.value = res.data.list;
    });
};

//表单相关---------------------------------------
interface RuleForm {
    id: string;
    name: string;
    isdel: number;
    gslx: string;
    uname: string;
    province: string;
    city: string;
    area: string;
    cltime: string;
    code: string;
    address: string;
    telphone: string;
    jyfw: string;
    yyzz: string;
    jyxkz: string;
    username: string;
    password: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<RuleForm>({
    id: "",
    name: "",
    isdel: 1,
    gslx: "",
    uname: "",
    cltime: "",
    code: "",
    province: "青海省",
    city: "",
    area: "",
    address: "",
    telphone: "",
    jyfw: "",
    yyzz: "",
    jyxkz: "",
    username: "",
    password: "",
});

const rules = reactive<FormRules<RuleForm>>({
    name: [{ required: true, message: "请填写公司名称", trigger: "blur" }],
    gslx: [{ required: true, message: "请填写公司类型", trigger: "blur" }],
    uname: [{ required: true, message: "请填写法人", trigger: "blur" }],
    cltime: [{ required: true, message: "请选择成立日期", trigger: "blur" }],
    city: [{ required: true, message: "请选择所属市", trigger: "blur" }],
    area: [{ required: true, message: "请选择所属区县", trigger: "blur" }],
    code: [
        { required: true, message: "请填写社会统一信用代码", trigger: "blur" },
    ],
    address: [{ required: true, message: "请填写注册地址", trigger: "blur" }],
    telphone: [{ required: true, message: "请填写联系电话", trigger: "blur" }],
    jyfw: [{ required: true, message: "请填写经营范围", trigger: "blur" }],
    yyzz: [{ required: true, message: "请上传营业执照", trigger: "blur" }],
    jyxkz: [{ required: true, message: "请上传经营许可证", trigger: "blur" }],
    username: [{ required: true, message: "请填写登录账号", trigger: "blur" }]
});

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            post({
                url: ruleForm.id
                    ? "/api/danwei/edit"
                    : "/api/danwei/add",
                data: toRaw(ruleForm),
            }).then((res: any) => {
                ElMessage.success("操作成功!");
                getdata();
                showflag.value = false;
                resetdata();
            });
        } else {
            console.log("error submit!");
        }
    });
};
//表单END---------------------------------------

//图片上传----------------------

const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    ruleForm.yyzz = response.data.fullurl;
};
const handleAvatarSuccess2: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    ruleForm.jyxkz = response.data.fullurl;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("只能上传jpg或png格式的图片!");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("图片大小不能超过 2MB!");
        return false;
    }
    return true;
};

//上传end----------------------

const resetdata = () => {
    Object.assign(ruleForm, {
        id: "",
        name: "",
        isdel: 1,
        gslx: "",
        uname: "",
        cltime: "",
        code: "",
        province: "青海省",
        city: "",
        area: "",
        address: "",
        telphone: "",
        jyfw: "",
        yyzz: "",
        jyxkz: "",
        username:'',
        password:'',
    });
    yyzzupload.value.clearFiles();
    jyxkzupload.value.clearFiles();
    isedit.value = true;
    title.value = "新增公司";
};

// 通过 defineExpose 暴露给父组件
defineExpose({
    showflag,
    title,
    isedit,
    device_id,
    ruleForm,
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
    margin-bottom: 30px;
    width: 50%;
}
.linebox {
    display: flex;
    align-items: flex-start;
    width: 100%;
}
:deep(.avatar-uploader .avatar) {
    width: 178px;
    height: 178px;
    display: block;
}
:deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
